import React, {Component} from "react";
import {Card, Icon, Modal, Button, message, Table} from 'antd';
import {reqUsers, reqDeleteUser, reqAddOrUpdateUser} from '../../api/index';
import LinkButton from "../../components/link-button";
import {formateDate} from "../../utils/dateUtils";
import {PAGE_SIZE} from "../../utils/constant";
import UserForm from "./user-form";

const { confirm } = Modal;

export default class User extends Component {
    state = {
        users: [],
        roles: [],
        isShow: false
    };

    initColumns = () => {
        this.columns = [
            {
                title: '用户名',
                dataIndex: 'username'
            },
            {
                title: '邮箱',
                dataIndex: 'email'
            },
            {
                title: '电话',
                dataIndex: 'phone'
            },
            {
                title: '注册时间',
                dataIndex: 'create_time',
                render: (create_time) => formateDate(create_time)
            },
            {
                title: '所属角色',
                dataIndex: 'role_id',
                render: (role_id) => this.roleNames[role_id]
            },
            {
                title: '操作',
                width: 300,
                render: (user) => (
                    <span>
                        <LinkButton onClick={() => this.showUpdate(user)}>修改</LinkButton>
                        <LinkButton onClick={() => this.deleteUser(user)}>删除</LinkButton>
                    </span>
                )
            }
        ];
    };

    showUpdate = (user) => {
        this.user = user;
        this.setState({
            isShow: true
        })
    };

    showAdd = () => {
        this.setState({isShow:true});
        this.user = null;
    };

    deleteUser = async (user) => {
        confirm({
            title: `确定要删除${user.username}吗？`,
            okText: "确认",
            cancelText: "取消",
            onOk: async ()=> {
                const result = await reqDeleteUser(user._id);
                if (result.status === 0) {
                    message.success('删除用户成功')
                } else {
                    message.error('删除用户成功')
                }
                this.getUsers()
            }
        });
    };

    handleCancel = () => {
        this.form.resetFields();
        this.setState({isShow: false});
    };

    addOrUpdateUser = () => {
        this.form.validateFields(async (err, values) => {
            if (!err) {
                this.setState({isShow: false});
                const user = values;
                if (this.user) {
                    user._id = this.user._id;
                }

                this.form.resetFields();
                const result = await reqAddOrUpdateUser(user);
                if (result.status === 0) {
                    message.success(this.user ? '修改用户成功' : '创建用户成功');
                    this.getUsers();
                } else {
                    message.error(this.user ? '修改用户失败' : '创建用户失败');
                }
            }
        });
    };

    getUsers = async () => {
        const result = await reqUsers();
        if (result.status === 0) {
            const {users,roles} = result.data;
            this.initRoleNames(roles);
            this.setState({users,roles});
        }
    };

    initRoleNames = (roles) => {
        const roleNames = roles.reduce((pre, role) => {
            pre[role._id] = role.name;
            return pre;
        }, {});
        this.roleNames = roleNames;
    };

    componentWillMount() {
        this.initColumns();
    }

    componentDidMount() {
        this.getUsers();
    }

    render() {
        const title = <Button type='primary' onClick={this.showAdd}>创建用户</Button>;
        const {users, isShow, roles} = this.state;
        const user = this.user;
        return (
            <Card title={title}>
                <Table
                    dataSource={users}
                    columns={this.columns}
                    bordered
                    rowKey='_id'
                    pagination={{defaultPageSize:PAGE_SIZE, showQuickJumper:true}}
                />

                <Modal
                    title= {user ? "修改用户" : "添加用户"}
                    visible={isShow}
                    onOk={this.addOrUpdateUser}
                    onCancel={this.handleCancel}
                    okText="确定"
                    cancelText="取消"
                >
                    <UserForm setForm={(form)=>{this.form = form}} roles={roles} user={user}>添加/更新界面</UserForm>
                </Modal>
            </Card>
        );
    }
}